package com.haojie.client;

import com.haojie.common.RPCRequest;
import com.haojie.common.RPCResponse;
import lombok.AllArgsConstructor;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

@AllArgsConstructor
public class SimpleRPCClient implements RPCClient {
    private String host;
    private int port;

    public RPCResponse sendRequest(RPCRequest request) {
        try {
            Socket socket = new Socket(this.host, this.port);

            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

            System.out.println(request);
            out.writeObject(request);
            out.flush();

            RPCResponse response = (RPCResponse) in.readObject();
            return response;
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
